package com.liuzhiqiang.oauth.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
public class TestController {


    @Autowired
    private ConsumerTokenServices consumerTokenServices;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @GetMapping("/test")
    public String test() {
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        return "测试 需要认证访问的接口";
    }


    @GetMapping("/test1")
    @PreAuthorize("hasAnyAuthority('admin')")
    public String test1() {
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        return "测试 已授权访问的接口";
    }

    @GetMapping("/test2")
    @PreAuthorize("hasAnyAuthority('user')")
    public String test2() {
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        return "测试 未授权访问的接口";
    }

    @GetMapping("/test3")
    public String test3() {
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        return "测试 可匿名访问的接口";
    }

    /**
     * 退出
     *
     * @return
     */
    @GetMapping("/exit")
    public String exit() {
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        String token = httpServletRequest.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        consumerTokenServices.revokeToken(token);
        log.info("当前登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
        return "已退出，token已清除";
    }
}
